import axios from 'axios';
import qs from 'qs';
import conf from 'conf/index';
import router from '../router/index'

axios.defaults.baseURL = `${conf.baseApiPath}/yyfn-api`;
let isShowIngError = false;

axios.interceptors.response.use(
  function ({
    data,
    config,
    status
  }) {
    // Do something with response data
    if (status === 200) {
      if (data.success) {
        return Promise.resolve(data.data);
      } else if (!data.success && data.desc && data.desc.indexOf('oken') != -1) {
        window.sessionStorage.removeItem('accessToken')
        router.push('/')
      } else {
        if (config.ignoreErrorModal) {
          return Promise.reject(data);
        } else {
          return Promise.reject(data.desc);
        }
      }
    } else {
      return Promise.reject(data);
    }
  },
  function (error) {
    console.log('axios error=', error);
    if (!isShowIngError) {
      isShowIngError = true;
    }
    if (error && error.response && error.response.status === 404) {
      error = 404;
    }
    // FIXME: xhr.js 接口404 没有提示网络出错
    return Promise.reject(error);
  }
);


export default {
  get(url, params = {}, config = {}) {
    return axios({
      method: 'get',
      url,
      params: {
        ...params,
        accessToken: window.sessionStorage.getItem('accessToken') || ''
      },
      ignoreErrorModal: config.ignoreErrorModal || false,
      headers: {
        'X-Requested-With': 'XMLHttpRequest'
      }
    });
  },
  post(url, data, config = {}) {
    let headers = {
      'X-Requested-With': 'XMLHttpRequest',
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    };
    return axios({
      method: 'post',
      url: url,
      data: qs.stringify({
        ...data,
        accessToken: window.sessionStorage.getItem('accessToken') || ''
      }, {
        arrayFormat: 'brackets'
      }),
      ignoreErrorModal: config.ignoreErrorModal || false,
      headers
    });
  }

};